package de.bmuskalla.brainfuck.ui.launch;

import java.io.IOException;
import java.io.InputStream;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.ui.ILaunchShortcut;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.part.FileEditorInput;

import de.bmuskalla.brainfuck.BFInterpreter;

public class BFLaunchShortcut implements ILaunchShortcut {

	public void launch(ISelection selection, String mode) {
		System.out.println(selection);
	}

	public void launch(IEditorPart editor, String mode) {
		BFInterpreter bf = new BFInterpreter();
		InputStream contents = null;
		try {
			contents = ((FileEditorInput) editor.getEditorInput()).getFile()
					.getContents();
			bf.load(slurp(contents));
			bf.run(false);
		} catch (CoreException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(((FileEditorInput) editor.getEditorInput())
				.getFile().getFullPath());
	}

	public static String slurp(InputStream in) throws IOException {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}

}
